package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.dao.ShoppingCartDao;
import com.reggie.pojo.ShoppingCart;
import com.reggie.service.ShoppingCartService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Override
    public void add(ShoppingCart shoppingCart) {
        shoppingCartDao.insert(shoppingCart);
    }

    @Override
    public List<ShoppingCart> selectAll(HttpServletRequest request) {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, request.getSession().getAttribute("user"));
        return shoppingCartDao.selectList(lqw);
    }

    @Override
    public Boolean subShoppingCart(ShoppingCart shoppingCart) {
        if (shoppingCart.getDishId() != null && shoppingCart.getSetmealId() == null) {
            int i = shoppingCartDao.subShoppingCartByDishId(shoppingCart.getDishId());
            return i > 0;
        } else if (shoppingCart.getDishId() == null && shoppingCart.getSetmealId() != null) {
            int i = shoppingCartDao.subShoppingCartBySetMealId(shoppingCart.getSetmealId());
            return i > 0;
        } else {
            return true;
        }
    }

    @Override
    public Boolean deleteAll() {
        List<ShoppingCart> shoppingCarts = shoppingCartDao.selectList(null);
        List<Long> list = new ArrayList<>();
        shoppingCarts.forEach((item) -> list.add(item.getId()));
        return shoppingCartDao.deleteBatchIds(list) > 0;
    }

    @Override
    public ShoppingCart selectById(Long id) {
        return shoppingCartDao.selectById(id);
    }

    @Override
    public List<ShoppingCart> selectByUserId(Long id) {
        return shoppingCartDao.selectByUserId(id);
    }

    @Override
    public int deleteByUserId(Long id) {
        return shoppingCartDao.deleteByUserId(id);
    }
}
